package birdsong.spamfilter;
import birdsong.comm.ServerComm;
import birdsong.comm.ServerSideMessage;

public abstract class SpamFilter implements ServerComm{
	private ServerComm decoratedServerComm;
	private String[] sensitiveWords;

	/**
	 * Creation of the SpamFilter
	 * 
	 * @param decoratedServerComm the interface ServerComm to be decorated.
	 * @param sensitiveWords a String containing the words that, if present, make the 
	 * SpamFilter reject the message and not pass it on to the server.
	 * 
	 */

	public SpamFilter(ServerComm decoratedServerComm, String[] sensitiveWords){
		this.decoratedServerComm = decoratedServerComm;
		this.sensitiveWords = sensitiveWords;
	}

	@Override
	public void start(){
		decoratedServerComm.start();
	}

	@Override
	public ServerSideMessage getNextMessage(){

		boolean permited = true;
		ServerSideMessage message;
		
		do{
			message = this.decoratedServerComm.getNextMessage();
			permited = sensitiveWordChecker(message);
			
		}while(!permited);
		
		return message;

	}

	/**
	 * 
	 * @param message 
	 * @param permited boolean variable used to control if a certain message is allowed to
	 * pass on to the server.
	 * 
	 */
	private boolean sensitiveWordChecker(ServerSideMessage message) {
		boolean permited = true;
		if(message!=null){
			for(int i=0; i < sensitiveWords.length && permited;i++){
				permited = !message.getPayload().contains(sensitiveWords[i]);
				System.out.println("Comparing the message against " + sensitiveWords[i]);
			}
		}
		return permited;
	}

	@Override
	public boolean hasNextMessage() {
		return decoratedServerComm.hasNextMessage();
	}

	@Override
	public void sendBirdsongMessage(String fromNicename, String toNickname,
			String birdsongMessage) {
		decoratedServerComm.sendBirdsongMessage(fromNicename, toNickname, birdsongMessage);
	}

	@Override
	public void sendNewFollower(String toNickname, String newFollower) {
		decoratedServerComm.sendNewFollower(toNickname, newFollower);
	}

	@Override
	public void sendNewUnfollow(String toNickname, String unfollower) {
		decoratedServerComm.sendNewUnfollow(toNickname, unfollower);

	}

	@Override
	public void sendError(String toNickname, String error) {
		decoratedServerComm.sendError(toNickname, error);
	}

	@Override
	public void sendClientConnected(String toNickname, String connectedNickname) {
		decoratedServerComm.sendClientConnected(toNickname, connectedNickname);
	}

	@Override
	public void sendClientDisconnected(String toNickname,
			String disconnectedNickname) {
		decoratedServerComm.sendClientDisconnected(toNickname, disconnectedNickname);

	}

	@Override
	public boolean clientIsConnected(String nickname) {
		return decoratedServerComm.clientIsConnected(nickname);
	}

	@Override
	public void disconnectClient(String nickname) {
		decoratedServerComm.disconnectClient(nickname);
	}
}
